package cn.kgc.controllers;

import cn.kgc.pojo.Pet;
import cn.kgc.pojo.User;
import cn.kgc.service.PetService;
import cn.kgc.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/main")
public class MyController {

    @Autowired
    private UserService userService;
    @Autowired
    private PetService petService;

    @RequestMapping("/login")
    public String login(@RequestParam("name") String username, @RequestParam("pwd") String pwd){
        User user = userService.login(username, pwd);
        System.out.println("username:"  + username
         + "\t" + "password:" + pwd + "\t" + "---------------------");
        if(user == null){
            return "login";
        }else{
            return "redirect:/main/show";
        }
    }

    @RequestMapping("/show")
    public String show(Model model,
                       @RequestParam(value="pageIndex", required = false, defaultValue="1")Integer pageIndex){
        PageHelper.startPage(pageIndex, 5);
        List<Pet> petAllList = petService.findAllPetList();
        PageInfo<Pet> pageInfo = new PageInfo<>(petAllList);
        model.addAttribute("pageInfo", pageInfo);
        return "/index";
    }

    @RequestMapping("/select")
    public String select(@RequestParam(value="name",required = false)String name,
                         @RequestParam(value="number", required = false)String num,
                         Model model,
                         @RequestParam(value="pageIndex", required = false, defaultValue="1")Integer pageIndex){

        System.out.println("name: " + name + "\t" + "num: " + num + "\t" +
                "pageIndex: " + pageIndex + "-----------------------------");
        PageHelper.startPage(pageIndex, 5);
        List<Pet> petList = petService.findPetByNameOrNumber(name, num);
        System.out.println("列表遍历:");
        for (Pet pet : petList) {
            System.out.println(pet.toString());
        }
        PageInfo<Pet> pageInfo = new PageInfo<>(petList);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("name", name);
        model.addAttribute("number", num);
        System.out.println("end****************");
        return "/index";
    }


}
